<script setup>
import { ref, onMounted, computed } from 'vue'
import { getAllTeachersAPI, addTeacherAPI, updateTeacherAPI, deleteTeacherAPI } from '@/api/admin'
import { ElMessage } from 'element-plus'

const teacherList = ref([])
const loading = ref(false)

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = computed(() => teacherForm.value.teacherId ? '编辑教师' : '新增教师')
const teacherForm = ref({
  teacherId: null,
  teacherNo: '',
  name: '',
  gender: '',
  email: '',
  phone: '',
  department: ''
})
const formRef = ref(null)

// 表单校验规则
const rules = {
  teacherNo: [
    { required: true, message: '请输入教师编号', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
  ],
  phone: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的电话号码', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请输入所属院系', trigger: 'blur' }
  ]
}

// 获取所有教师列表
const getAllTeachers = async () => {
  loading.value = true
  try {
    const { data } = await getAllTeachersAPI()
    if (data.code === 200) {
      teacherList.value = data.data
    } else {
      ElMessage.error(data.msg || '获取教师列表失败')
    }
  } catch (error) {
    console.error('获取教师列表失败:', error)
    ElMessage.error('获取教师列表失败')
  } finally {
    loading.value = false
  }
}

// 显示新增/编辑弹窗
const showDialog = (teacher = null) => {
  if (teacher) {
    // 编辑
    teacherForm.value = { ...teacher }
  } else {
    // 新增
    teacherForm.value = {
      teacherId: null,
      teacherNo: '',
      name: '',
      gender: '',
      email: '',
      phone: '',
      department: ''
    }
  }
  dialogVisible.value = true
}

// 确认新增/编辑
const confirmDialog = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const api = teacherForm.value.teacherId ? updateTeacherAPI : addTeacherAPI
        if(!teacherForm.value.teacherId){
          delete teacherForm.value.teacherId
        }
        const { data } = await api(teacherForm.value)

        if (data.code === 200) {
          ElMessage.success(teacherForm.value.teacherId ? '教师信息更新成功！' : '教师添加成功！')
          dialogVisible.value = false
          getAllTeachers() // 刷新列表
        } else {
          ElMessage.error(data.msg || (teacherForm.value.teacherId ? '教师信息更新失败' : '教师添加失败'))
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 删除教师
const deleteTeacher = async (teacherId) => {
  loading.value = true
  try {
    const { data } = await deleteTeacherAPI(teacherId)
    if (data.code === 200) {
      ElMessage.success('教师删除成功！')
      getAllTeachers() // 刷新列表
    } else {
      ElMessage.error(data.msg || '教师删除失败')
    }
  } catch (error) {
    console.error('教师删除失败:', error)
    ElMessage.error('教师删除失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  getAllTeachers()
})
</script>
<template>
  <div class="teacher-management-container">
    <div class="header">
      <h2>教师管理</h2>
      <el-button type="primary" @click="showDialog()">新增教师</el-button>
    </div>

    <el-table v-loading="loading" :data="teacherList" style="width: 100%">
      <el-table-column prop="teacherId" label="ID" width="80" />
      <el-table-column prop="teacherNo" label="教师编号" width="120" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="gender" label="性别" width="80" />
      <el-table-column prop="email" label="邮箱" width="180" />
      <el-table-column prop="phone" label="电话" width="150" />
      <el-table-column prop="department" label="所属院系" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="showDialog(scope.row)">编辑</el-button>
          <el-popconfirm
            title="确定删除该教师吗？"
            confirm-button-text="确定"
            cancel-button-text="取消"
            @confirm="deleteTeacher(scope.row.teacherId)"
          >
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑教师弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="teacherForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="教师编号" prop="teacherNo">
          <el-input v-model="teacherForm.teacherNo" placeholder="请输入教师编号" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="teacherForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="teacherForm.gender" placeholder="请选择性别">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="teacherForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="teacherForm.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="所属院系" prop="department">
          <el-input v-model="teacherForm.department" placeholder="请输入所属院系" />
        </el-form-item>
        <!-- 编辑时可能需要禁用教师编号和ID字段 -->
         <el-form-item v-if="teacherForm.teacherId" label="ID">
            <el-input v-model="teacherForm.teacherId" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmDialog">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>


<style scoped>
.teacher-management-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

h2 {
  margin: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 